<?php

namespace App\Admin\Controllers;

use App\Models\Station;
use App\Models\Order;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\InfoBox;
use Encore\Admin\Widgets\Table;

class StationController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('门店')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        $station = Station::findOrFail($id);
        return $content
            ->header('门店')
            ->description('详细信息')
            ->row(function (Row $row) use ($station) {
                //基本信息
                $content = sprintf(
                    '<div style="display: flex;justify-content: center"><div><img src="%s" class="img-md" /></div><div class="text-center"><h4>%s</h4><h5 class="text-muted">位置：%s</h5></div></div>',
                    \Storage::url($station->coverPath), $station->name, $station->address
                );
                $row->column(4, $content);

                //洗车舱数
                $carbarnCount = $station->carbarns()->count();
                $content = sprintf('<div class="text-center"><h4>洗车舱数</h4><h1>%s</h1></div>', $carbarnCount);
                $row->column(2, $content);

                //订单总量
                $orderCount = $station->orders()->count();
                $content = sprintf('<div class="text-center"><h4>订单总量</h4><h1>%s</h1></div>', $orderCount);
                $row->column(2, $content);

                //总收入
                $orderIncome = $station->orders()->sum("amount");
                $content = sprintf('<div class="text-center"><h4>总收入</h4><h1>%s</h1></div>', $orderIncome);
                $row->column(2, $content);

                //操作按钮
                $content = sprintf(
                    '<div class="text-center" style="padding-top: 20px;"><form method="post" action="%s"><input type="hidden" value="%s" name="id" />%s<button class="btn btn-lg btn-%s">%s</button></form></div>',
                    route('station.toggle-status'),
                    $station->id,
                    csrf_field(),
                    $station->isOpen() ? "danger" : "success",
                    $station->isOpen() ? "关闭" : "打开"
                );
                $row->column(2, $content);
            })
            ->row(function (Row $row) use ($station) {

                $row->column(12, '<hr style="height: 1px;background-color: #ddd"/>');

            })
            ->row(function (Row $row) use ($station) {

                //今日订单
                $orderCount = $station->orders()->where("addTime", ">=", strtotime('today'))->count();
                $box = new InfoBox('今日订单', 'list-alt', 'blue', route('order.index'), $orderCount);
                $row->column(6, $box);

                //今日收入
                $orderIncome = $station->orders()->where("addTime", ">=", strtotime('today'))->sum("amount");
                $box = new InfoBox('今日收入', 'money', 'blue', route('order.index'), $orderIncome);
                $row->column(6, $box);

            })
            ->row(function (Row $row) use ($station) {

                //洗车舱信息
                $carbarnList = $station->carbarns()->get();
                $carbarnIdArr = $carbarnList->pluck("id")->all();
                //订单总量
                $orderTotal = Order::whereIn("carbarnId", $carbarnIdArr)->groupBy("carbarnId")
                    ->selectRaw("carbarnId, count(*) as counts")->get()->pluck("counts", "carbarnId");
                $orderToday = Order::whereIn("carbarnId", $carbarnIdArr)->where("addTime", ">=" ,strtotime('today'))
                    ->groupBy("carbarnId")->selectRaw("carbarnId, count(*) as counts")->get()->pluck("counts", "carbarnId");
                $data = [];
                $carbarnList->each(function ($item) use (&$data, $orderTotal, $orderToday) {
                    $data[] = [
                        sprintf('<img src="%s" class="img-sm" />', \Storage::url($item->coverPath)),
                        $item->name,
                        $item->longitude,
                        $item->latitude,
                        $item->address,
                        $orderTotal->get($item->id),
                        $orderToday->get($item->id),
                    ];
                });
                $headers = ['封面', '名称', '经度', '纬度', '地址', '订单总量', '今日订单'];
                $table = new Table($headers, $data);
                $box = new Box('投放的洗车舱', $table);

                $row->column(12, $box->solid()->style('primary'));
            });
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑')
            ->description('门店')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('门店')
            ->description('创建')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Station);
        $grid->model()->orderBy('id', 'desc');
        $grid->id('Id');
        $grid->coverPath('封面图')->display(function () {
           return sprintf('<img src="%s" class="img-sm" />', \Storage::url($this->coverPath));
        });
        $grid->name('名称');
        $grid->address('地址');
        $grid->longitude('经度');
        $grid->latitude('纬度');
        $grid->addTime('添加时间')->display(function ($item) {
            $addTimeOriginal = $this->getOriginal('addTime');
            if ($addTimeOriginal) {
                return $this->addTime->toDateTimeString();
            }
            return '';
        });
        $grid->statusText('状态')->display(function () {
            return sprintf(
                '<span class="label label-%s">%s</span>',
                $this->isOpen() ? "info" : "warning",
                $this->isOpen() ? "正常营业" : "关闭"
            );
        });

        $grid->disableExport();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Station);

        $form->text('name', '名称')->rules(['required']);
        $form->text('address', '地址')->rules(['required']);
        $form->text('longitude', '经度')->rules(['required']);
        $form->text('latitude', '纬度')->rules(['required']);
        $form->image('coverPath', '封面图')->rules('required')->uniqueName();

        return $form;
    }

    public function topToday()
    {
        $topStation = Order::where("mcstationId", ">", 0)
            ->where("addTime", ">=", strtotime('today'))
            ->orderByRaw("count(mcstationId) desc")->groupBy("mcstationId")->selectRaw("mcstationId, count(mcstationId) as counts")->get();

        $topStationOrderCounts = $topStation->pluck('counts', 'mcstationId');

        $stationList = Station::whereIn("id", $topStation->pluck("mcstationId")->all())
            ->get()->each(function (&$item) use ($topStationOrderCounts) {
                $item->order_counts = $topStationOrderCounts->get($item->id);
            });

        return response()->json($stationList->toArray());
    }

    public function toggleStatus()
    {
        $id = request('id');
        $station = Station::findOrFail($id);
        if ($station->isOpen())
        {
            $station->status = Station::STATUS_CLOSED;
        }
        else
        {
            $station->status = Station::STATUS_OPEN;
        }
        $station->save();
        admin_toastr('状态切换成功', 'success');
        return back();
    }
}
